<template>
  <!-- 主要的协议配置 Drawer -->
  <a-drawer
    :open="showEditDrawer"
    :title="drawerTitle"
    width="1400px"
    placement="right"
    :closable="true"
    @close="handleCloseDrawer"
    class="protocol-config-drawer"
  >

    <a-form
      ref="protocolFormRef"
      :model="protocolForm"
      :rules="protocolRules"
      layout="vertical"
    >
      <a-card class="edit-section" title="基本信息" :bordered="false">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="协议名称" name="name">
              <a-input
                v-model:value="protocolForm.name"
                placeholder="请输入协议名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="协议类型" name="protocolType">
              <a-select
                v-model:value="protocolForm.protocolType"
                placeholder="请选择协议类型"
                @change="handleProtocolTypeChange"
              >
                <a-select-option value="MERCHANT_CHANNEL_CONFIG_V3">商户渠道配置</a-select-option>
                <a-select-option value="QR_CODE_CONFIG">二维码配置</a-select-option>
                <a-select-option value="DEFAULT_PROTOCOL">默认协议</a-select-option>
                <a-select-option value="CHANNEL_ONBOARDING">渠道进件协议</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="版本号" name="version">
              <a-input
                v-model:value="protocolForm.version"
                placeholder="请输入版本号"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="状态" name="enabled">
              <a-radio-group
                v-model:value="protocolForm.enabled"
                button-style="solid"
              >
                <a-radio-button :value="true">启用</a-radio-button>
                <a-radio-button :value="false">禁用</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="渠道代码" name="channelCode">
              <a-input
                v-model:value="protocolForm.channelCode"
                placeholder="请输入渠道代码"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="protocolForm.protocolType === 'QR_CODE_CONFIG'">
            <a-form-item label="二维码类型" name="codeType">
              <a-select
                v-model:value="protocolForm.codeType"
                placeholder="请选择二维码类型"
              >
                <a-select-option value="STATIC">静态二维码</a-select-option>
                <a-select-option value="DYNAMIC">动态二维码</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="protocolForm.description"
            placeholder="请输入协议描述"
            :rows="3"
          />
        </a-form-item>
      </a-card>

      <a-card class="edit-section" title="配置段管理" :bordered="false">
        <div class="config-sections-manager">
          <div class="sections-toolbar">
            <a-button type="dashed" @click="handleAddSection">
              <PlusOutlined /> 添加配置段
            </a-button>
          </div>

          <div class="sections-list">
            <div
              v-for="(section, index) in protocolForm.configSections"
              :key="`section-${index}`"
              class="section-item"
            >
              <a-row :gutter="8" align="middle">
                <a-col :span="4">
                  <div class="section-name">
                    <strong>{{ section.sectionName || '未命名段' }}</strong>
                  </div>
                </a-col>
                <a-col :span="3">
                  <div class="section-key">
                    {{ section.sectionKey || 'no-key' }}
                  </div>
                </a-col>
                <a-col :span="2">
                  <a-tag size="small" color="blue">
                    {{ section.fields?.length || 0 }} 字段
                  </a-tag>
                </a-col>
                <a-col :span="6">
                  <div class="section-description">
                    {{ section.description || '暂无描述' }}
                  </div>
                </a-col>
                <a-col :span="6">
                  <div class="section-fields-preview">
                    <a-tag
                      v-for="field in section.fields?.slice(0, 3) || []"
                      :key="field.fieldKey"
                      size="small"
                      class="field-preview-tag"
                    >
                      {{ field.fieldName || field.fieldKey }}
                    </a-tag>
                    <a-tag v-if="(section.fields?.length || 0) > 3" size="small" color="default">
                      +{{ (section.fields?.length || 0) - 3 }}
                    </a-tag>
                    <span v-if="!section.fields || section.fields.length === 0" class="no-fields">
                      暂无字段
                    </span>
                  </div>
                </a-col>
                <a-col :span="3">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleEditSection(index)"
                    >
                      <EditOutlined /> 编辑
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      danger
                      @click="handleRemoveSection(index)"
                    >
                      <DeleteOutlined />
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </div>
          </div>
        </div>
      </a-card>
    </a-form>

    <!-- 底部操作按钮 -->
    <div class="drawer-footer">
      <a-space>
        <a-button @click="handleCloseDrawer">取消</a-button>
        <a-button type="primary" @click="handleSaveProtocol">保存</a-button>
      </a-space>
    </div>
  </a-drawer>

  <!-- 段配置对话框 -->
  <a-modal
    v-model:open="showSectionDialog"
    :title="sectionDialogTitle"
    width="1000px"
    ok-text="保存"
    cancel-text="取消"
    @ok="handleSaveSection"
    @cancel="handleCancelSection"
  >
    <a-form
      ref="sectionFormRef"
      :model="editingSection"
      :rules="sectionRules"
      layout="vertical"
    >
      <a-card title="段基本信息" :bordered="false" style="margin-bottom: 16px;">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="段变量名" name="sectionKey">
              <a-input
                v-model:value="editingSection.sectionKey"
                placeholder="请输入段变量名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="段显示名" name="sectionName">
              <a-input
                v-model:value="editingSection.sectionName"
                placeholder="请输入段显示名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="排序" name="order">
              <a-input-number
                v-model:value="editingSection.order"
                :min="1"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="段描述" name="description">
          <a-textarea
            v-model:value="editingSection.description"
            placeholder="请输入段描述"
            :rows="2"
          />
        </a-form-item>
      </a-card>

      <a-card title="字段管理" :bordered="false">
        <div class="section-fields-manager">
          <div class="fields-toolbar">
            <a-button type="dashed" @click="handleAddFieldInSection">
              <PlusOutlined /> 添加字段
            </a-button>
          </div>

          <div class="fields-list">
            <div
              v-for="(field, fieldIndex) in editingSection.fields"
              :key="`section-field-${fieldIndex}`"
              class="field-item"
            >
              <a-row :gutter="8">
                <a-col :span="3">
                  <a-input
                    v-model:value="field.fieldKey"
                    placeholder="字段ID"
                  />
                </a-col>
                <a-col :span="3">
                  <a-input
                    v-model:value="field.fieldName"
                    placeholder="字段标签"
                  />
                </a-col>
                <a-col :span="3">
                  <a-select
                    v-model:value="field.fieldType"
                    placeholder="类型"
                    style="width: 100%;"
                    :dropdown-style="{ minWidth: '120px' }"
                    @change="(value) => handleFieldTypeChange(field, value)"
                  >
                    <a-select-option :value="FieldType.INPUT">文本</a-select-option>
                    <a-select-option :value="FieldType.NUMBER">数字</a-select-option>
                    <a-select-option :value="FieldType.SWITCH">开关</a-select-option>
                    <a-select-option :value="FieldType.SELECT">下拉选择</a-select-option>
                    <a-select-option :value="FieldType.RADIO">单选按钮</a-select-option>
                    <a-select-option :value="FieldType.CHECKBOX">复选框</a-select-option>
                    <a-select-option :value="FieldType.TEXTAREA">多行文本</a-select-option>
                    <a-select-option :value="FieldType.PASSWORD">密码</a-select-option>
                    <a-select-option :value="FieldType.UPLOAD">上传</a-select-option>
                    <a-select-option :value="FieldType.URL">链接</a-select-option>
                    <a-select-option :value="FieldType.EMAIL">邮箱</a-select-option>
                    <a-select-option :value="FieldType.DATE">日期</a-select-option>
                    <a-select-option :value="FieldType.DATETIME">日期时间</a-select-option>
                    <a-select-option :value="FieldType.JSON">JSON</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-input
                    v-model:value="field.placeholder"
                    placeholder="占位符"
                  />
                </a-col>
                <a-col :span="3">
                  <!-- Switch类型字段使用开关组件 -->
                  <a-switch
                    v-if="field.fieldType === FieldType.SWITCH"
                    v-model:checked="field.defaultValue"
                    checked-children="是"
                    un-checked-children="否"
                  />
                  <!-- 数组类型默认值 -->
                  <a-input
                    v-else-if="Array.isArray(field.defaultValue)"
                    :value="Array.isArray(field.defaultValue) ? field.defaultValue.join(', ') : field.defaultValue"
                    placeholder="默认值"
                    @input="handleDefaultValueArrayChange(field, $event)"
                  />
                  <!-- 其他类型使用文本输入 -->
                  <a-input
                    v-else
                    v-model:value="field.defaultValue"
                    placeholder="默认值"
                  />
                </a-col>
                <a-col :span="2">
                  <a-checkbox v-model:checked="field.required">必填</a-checkbox>
                </a-col>
                <a-col :span="2">
                  <!-- 选项编辑按钮 -->
                  <a-button
                    v-if="needsOptions(field.fieldType)"
                    type="link"
                    size="small"
                    @click="handleEditOptions(field)"
                  >
                    选项
                  </a-button>
                </a-col>
                <a-col :span="2">
                  <a-button
                    type="link"
                    size="small"
                    danger
                    @click="handleRemoveFieldInSection(fieldIndex)"
                  >
                    <DeleteOutlined />
                  </a-button>
                </a-col>
              </a-row>
            </div>
          </div>

          <div v-if="editingSection.fields.length === 0" class="empty-fields">
            <a-empty description="暂无字段，请添加字段" />
          </div>
        </div>
      </a-card>
    </a-form>
  </a-modal>

  <!-- 选项编辑对话框 -->
  <a-modal
    v-model:open="showOptionsDialog"
    title="编辑选项"
    width="600px"
    ok-text="保存"
    cancel-text="取消"
    @ok="handleSaveOptions"
    @cancel="handleCancelOptions"
  >
    <div class="options-editor">
      <div class="options-toolbar">
        <a-button type="dashed" @click="handleAddOption">
          <PlusOutlined /> 添加选项
        </a-button>
      </div>

      <div class="options-list">
        <div
          v-for="(option, index) in editingOptions"
          :key="index"
          class="option-item"
        >
          <a-row :gutter="8" align="middle">
            <a-col :span="8">
              <a-input
                v-model:value="option.label"
                placeholder="显示文本"
              />
            </a-col>
            <a-col :span="8">
              <a-input
                v-model:value="option.value"
                placeholder="选项值"
              />
            </a-col>
            <a-col :span="4">
              <a-checkbox v-model:checked="option.disabled">禁用</a-checkbox>
            </a-col>
            <a-col :span="4">
              <a-button
                type="link"
                size="small"
                danger
                @click="handleRemoveOption(index)"
              >
                <DeleteOutlined />
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>

      <div v-if="editingOptions.length === 0" class="empty-options">
        <a-empty description="暂无选项，请添加选项" />
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
} from "@ant-design/icons-vue";
import { apiProtocolConfigAdd, apiProtocolConfigEdit } from "./api";
import {
  ProtocolType3,
  FieldType,
  type MerchantChannelConfig3,
  type QRCodeConfig,
  type DefaultProtocol,
  type ConfigSection,
  type ConfigField,
  ProtocolConfigUtils,
} from "../../types/protocol3-types";
import { ProtocolTypeNumber } from "./types";

// 选项接口定义
interface FieldOption {
  label: string;
  value: string;
  disabled?: boolean;
}

// 扩展ConfigField接口以支持选项
interface EnhancedConfigField extends ConfigField {
  options?: FieldOption[];
}

// Props定义
const props = defineProps({
  callbackFunc: { type: Function, default: () => {} }
});

// 响应式数据
const showEditDrawer = ref(false);
const showOptionsDialog = ref(false);
const showSectionDialog = ref(false);

// 组件引用
const protocolFormRef = ref();
const sectionFormRef = ref();

// 选项编辑相关
const editingField = ref<EnhancedConfigField | null>(null);
const editingOptions = ref<FieldOption[]>([]);

// 段编辑相关
const editingSectionIndex = ref<number>(-1);
const editingSection = reactive<ConfigSection>({
  sectionKey: "",
  sectionName: "",
  description: "",
  icon: "SettingOutlined",
  order: 1,
  collapsed: false,
  fields: [],
});

// 表单数据
const protocolForm = reactive<MerchantChannelConfig3 | QRCodeConfig>({
  protocolId: "",
  protocolType: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3,
  channelCode: "",
  name: "",
  version: "3.0.0",
  description: "",
  enabled: true,
  configSections: [],
  uiConfig: {
    layout: "horizontal",
    labelWidth: 120,
    showDescription: true,
    grouping: "sections",
  },
  metadata: {
    author: "AnyPay Team",
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
    tags: [],
    category: "自定义协议",
  },
});

// Drawer 标题
const drawerTitle = computed(() => {
  return protocolForm.protocolId ? "编辑协议配置" : "新增协议配置";
});

// 段对话框标题
const sectionDialogTitle = computed(() => {
  return editingSectionIndex.value >= 0 ? "编辑配置段" : "新增配置段";
});

// 表单验证规则
const protocolRules = {
  name: [{ required: true, message: "请输入协议名称", trigger: "blur" }],
  protocolType: [{ required: true, message: "请选择协议类型", trigger: "change" }],
  version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
  channelCode: [
    { pattern: /^[A-Z_][A-Z0-9_]*$/, message: "渠道代码只能包含大写字母、数字和下划线，且必须以字母或下划线开头", trigger: "blur" }
  ],
};

// 段表单验证规则
const sectionRules = {
  sectionKey: [
    { required: true, message: "请输入段变量名", trigger: "blur" },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: "段变量名只能包含字母、数字和下划线，且必须以字母或下划线开头", trigger: "blur" }
  ],
  sectionName: [{ required: true, message: "请输入段显示名", trigger: "blur" }],
  order: [{ required: true, message: "请输入排序", trigger: "blur" }],
};

// 判断字段类型是否需要选项配置
const needsOptions = (fieldType: string) => {
  return [FieldType.SELECT, FieldType.RADIO, FieldType.CHECKBOX].includes(fieldType as FieldType);
};

// 方法
const show = (record?: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  if (record && record.protocolId) {
    // 编辑模式
    handleEdit(record);
  } else {
    // 新增模式
    handleCreate();
  }
};

const handleCreate = () => {
  resetProtocolForm();
  showEditDrawer.value = true;
};

const handleEdit = (record: any) => {
  // 检查数据结构，如果有protocolData字段说明需要解析
  let actualData;
  if (record.protocolData && typeof record.protocolData === 'string') {
    // protocolData是JSON字符串，需要解析
    try {
      actualData = JSON.parse(record.protocolData);
      // 合并基本信息
      actualData.protocolId = record.protocolId;
      actualData.name = record.protocolName || actualData.name;

      // 处理protocolType数字转换
      let protocolType = record.protocolType || actualData.protocolType;
      if (typeof protocolType === 'number') {
        const typeMap = {
          [ProtocolTypeNumber.MERCHANT_CHANNEL_CONFIG]: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3,
          [ProtocolTypeNumber.QR_CODE_CONFIG]: ProtocolType3.QR_CODE_CONFIG,
          [ProtocolTypeNumber.DEFAULT_PROTOCOL]: ProtocolType3.DEFAULT_PROTOCOL
        };
        protocolType = typeMap[protocolType as keyof typeof typeMap] || ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3;
      }
      actualData.protocolType = protocolType;
      actualData.channelCode = record.channelCode || actualData.channelCode;
    } catch (error) {
      console.error('解析协议数据失败:', error);
      actualData = record;
    }
  } else {
    // 直接使用record
    actualData = record;
  }

  // 赋值到表单前，先处理字段类型兼容性
  const sanitizedData = sanitizeProtocolData(actualData);
  Object.assign(protocolForm, sanitizedData);
  showEditDrawer.value = true;
};

const handleCloseDrawer = () => {
  showEditDrawer.value = false;
  resetProtocolForm();
};

const handleProtocolTypeChange = (value: string) => {
  if (value === ProtocolType3.QR_CODE_CONFIG) {
    (protocolForm as QRCodeConfig).codeType = 'STATIC';
  }
};

const handleFieldTypeChange = (field: any, newType: string) => {
  // 当字段类型改变时，设置适当的默认值
  if (newType === FieldType.SWITCH) {
    field.defaultValue = false;
  } else if (field.fieldType === FieldType.SWITCH && newType !== FieldType.SWITCH) {
    // 从SWITCH类型改为其他类型，转换Boolean为字符串
    field.defaultValue = field.defaultValue ? "true" : "false";
  }

  // 如果新类型需要选项但当前没有选项，初始化空选项数组
  if (needsOptions(newType) && !field.options) {
    field.options = [];
  }

  field.fieldType = newType;
};

const handleAddSection = () => {
  // 重置编辑段数据
  resetEditingSection();
  editingSectionIndex.value = -1;
  showSectionDialog.value = true;
};

const handleEditSection = (index: number) => {
  const section = protocolForm.configSections[index];
  editingSectionIndex.value = index;

  // 深拷贝段数据到编辑表单
  Object.assign(editingSection, {
    sectionKey: section.sectionKey,
    sectionName: section.sectionName,
    description: section.description,
    icon: section.icon,
    order: section.order,
    collapsed: section.collapsed,
    fields: section.fields.map(field => ({ ...field })), // 深拷贝字段数组
  });

  showSectionDialog.value = true;
};

const handleRemoveSection = (index: number) => {
  protocolForm.configSections.splice(index, 1);
};

const handleSaveSection = async () => {
  try {
    await sectionFormRef.value?.validate();

    if (editingSectionIndex.value >= 0) {
      // 编辑模式：更新现有段
      Object.assign(protocolForm.configSections[editingSectionIndex.value], {
        ...editingSection,
        fields: editingSection.fields.map(field => ({ ...field })), // 深拷贝字段
      });
    } else {
      // 新增模式：添加新段
      const newSection: ConfigSection = {
        ...editingSection,
        fields: editingSection.fields.map(field => ({ ...field })), // 深拷贝字段
      };
      protocolForm.configSections.push(newSection);
    }

    showSectionDialog.value = false;
    message.success(editingSectionIndex.value >= 0 ? "段配置更新成功" : "段配置添加成功");
  } catch (error) {
    console.error('保存段配置失败:', error);
  }
};

const handleCancelSection = () => {
  showSectionDialog.value = false;
  resetEditingSection();
};

const resetEditingSection = () => {
  const sectionCount = protocolForm.configSections.length + 1;
  Object.assign(editingSection, {
    sectionKey: `section_${Date.now()}`,
    sectionName: `配置段${sectionCount}`,
    description: "",
    icon: "SettingOutlined",
    order: sectionCount,
    collapsed: false,
    fields: [],
  });
};

const handleAddFieldInSection = () => {
  const fieldKey = `field_${Date.now()}`;
  const newField: EnhancedConfigField = {
    fieldKey,
    fieldName: `字段${editingSection.fields.length + 1}`,
    fieldType: FieldType.INPUT,
    required: false,
    placeholder: `请输入内容`,
    defaultValue: "",
    options: [], // 初始化选项数组
  };
  editingSection.fields.push(newField);
};

const handleRemoveFieldInSection = (fieldIndex: number) => {
  editingSection.fields.splice(fieldIndex, 1);
};

// 选项编辑相关方法
const handleEditOptions = (field: EnhancedConfigField) => {
  editingField.value = field;
  editingOptions.value = field.options ? [...field.options] : [];
  showOptionsDialog.value = true;
};

const handleAddOption = () => {
  editingOptions.value.push({
    label: `选项${editingOptions.value.length + 1}`,
    value: `option_${editingOptions.value.length + 1}`,
    disabled: false
  });
};

const handleRemoveOption = (index: number) => {
  editingOptions.value.splice(index, 1);
};

const handleSaveOptions = () => {
  if (editingField.value) {
    editingField.value.options = [...editingOptions.value];
  }
  showOptionsDialog.value = false;
  editingField.value = null;
  editingOptions.value = [];
};

const handleCancelOptions = () => {
  showOptionsDialog.value = false;
  editingField.value = null;
  editingOptions.value = [];
};

const handleSaveProtocol = async () => {
  try {
    await protocolFormRef.value?.validate();

    // 准备保存的数据，需要转换为API期望的格式
    const isEdit = !!protocolForm.protocolId && protocolForm.protocolId !== "";

    // 构建保存数据
    const saveData = {
      protocolId: isEdit ? protocolForm.protocolId : `PROTOCOL3_${Date.now()}`,
      protocolName: protocolForm.name,
      protocolType: (protocolForm as any).protocolType === ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3 ? ProtocolTypeNumber.MERCHANT_CHANNEL_CONFIG :
                   (protocolForm as any).protocolType === ProtocolType3.QR_CODE_CONFIG ? ProtocolTypeNumber.QR_CODE_CONFIG :
                   (protocolForm as any).protocolType === ProtocolType3.DEFAULT_PROTOCOL ? ProtocolTypeNumber.DEFAULT_PROTOCOL :
                   ProtocolTypeNumber.MERCHANT_CHANNEL_CONFIG,
      channelCode: protocolForm.channelCode,
      protocolData: JSON.stringify({
        ...protocolForm,
        metadata: {
          ...protocolForm.metadata,
          updateTime: new Date().toISOString()
        }
      })
    };

    // 让后端自动处理时间字段，避免时间格式问题
    if (isEdit) {
      await apiProtocolConfigEdit(protocolForm.protocolId, saveData);
    } else {
      await apiProtocolConfigAdd(saveData);
    }

    message.success(isEdit ? "编辑协议成功" : "新增协议成功");
    showEditDrawer.value = false;

    // 调用回调函数通知父组件刷新数据
    if (props.callbackFunc) {
      props.callbackFunc();
    }
  } catch (error) {
    console.error('保存协议失败:', error);
    message.error("保存失败");
  }
};

const resetProtocolForm = () => {
  Object.assign(protocolForm, {
    protocolId: "",
    protocolType: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3,
    channelCode: "",
    name: "",
    version: "3.0.0",
    description: "",
    enabled: true,
    configSections: [],
    uiConfig: {
      layout: "horizontal",
      labelWidth: 120,
      showDescription: true,
      grouping: "sections",
    },
    metadata: {
      author: "AnyPay Team",
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      tags: [],
      category: "自定义协议",
    },
  });
};

// 处理数组类型的默认值输入
function handleDefaultValueArrayChange(field: any, event: any) {
  const value = event.target.value;
  if (value.trim() === '') {
    field.defaultValue = [];
  } else {
    // 按逗号分割并去除空白
    field.defaultValue = value.split(',').map((item: string) => item.trim()).filter((item: string) => item !== '');
  }
}

// 数据清理函数，确保字段类型兼容性
function sanitizeProtocolData(data: any) {
  if (!data || !data.configSections) {
    return data;
  }

  const sanitized = { ...data };

  // 处理配置段中的字段默认值
  sanitized.configSections = data.configSections.map((section: any) => ({
    ...section,
    fields: section.fields.map((field: any) => {
      const sanitizedField = { ...field };

      // 对于SWITCH类型字段，确保defaultValue是Boolean类型
      if (field.fieldType === FieldType.SWITCH) {
        if (typeof field.defaultValue === 'string') {
          sanitizedField.defaultValue = field.defaultValue === 'true' || field.defaultValue === '1';
        } else if (field.defaultValue === undefined || field.defaultValue === null) {
          sanitizedField.defaultValue = false;
        }
      }
      // 对于其他类型，确保defaultValue是字符串或数组
      else if (field.fieldType !== FieldType.SWITCH && typeof field.defaultValue === 'boolean') {
        sanitizedField.defaultValue = String(field.defaultValue);
      }

      // 确保需要选项的字段有options属性
      if (needsOptions(field.fieldType) && !sanitizedField.options) {
        sanitizedField.options = [];
      }

      return sanitizedField;
    })
  }));

  return sanitized;
}

// 暴露方法给父组件调用
defineExpose({
  show,
  handleCreate,
  handleEdit
});
</script>

<style scoped>
.protocol-config-drawer {
  .edit-section {
    margin-bottom: 16px;
  }

  .drawer-footer {
    position: absolute;
    bottom: 24px;
    right: 24px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.9);
    padding: 8px 16px;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.config-sections-manager {
  .sections-toolbar {
    margin-bottom: 16px;
  }

  .sections-list {
    .section-item {
      margin-bottom: 8px;
      padding: 12px;
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      background-color: #fafafa;
      transition: all 0.2s ease;

      &:hover {
        background-color: #f5f5f5;
        border-color: #d9d9d9;
      }

      .section-name {
        font-size: 14px;
        color: #262626;
      }

      .section-key {
        font-size: 12px;
        color: #8c8c8c;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      }

      .section-description {
        font-size: 12px;
        color: #595959;
        line-height: 1.4;
      }

      .section-fields-preview {
        .field-preview-tag {
          margin-right: 4px;
          margin-bottom: 2px;
        }

        .no-fields {
          font-size: 12px;
          color: #bfbfbf;
          font-style: italic;
        }
      }
    }
  }
}

.section-fields-manager {
  .fields-toolbar {
    margin-bottom: 16px;
  }

  .fields-list {
    .field-item {
      margin-bottom: 12px;
      padding: 12px;
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      background-color: #fafafa;
    }
  }

  .empty-fields {
    text-align: center;
    padding: 40px 0;
  }
}

.options-editor {
  .options-toolbar {
    margin-bottom: 16px;
  }

  .options-list {
    .option-item {
      margin-bottom: 12px;
      padding: 12px;
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      background-color: #fafafa;
    }
  }

  .empty-options {
    text-align: center;
    padding: 40px 0;
  }
}
</style>
